package kjx_test_security.auth;


import kjx_test_security.auth.components.ResetAuthenticationEntryPoint;
import kjx_test_security.auth.components.ResetAccessDeniedHandler;
import kjx_test_security.auth.constans.WhiteUrlsConstants;
import kjx_test_security.filter.JwtAuthenticationTokenFilter;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;

/**
 * @ClassName: WebSecurityConfig
 * @Description: spring security配置
 * @Author: 郭成兴
 * @Date 2021/8/11 8:22 下午
 * @Copyright 如皋市韶光科技有限公司
 **/
@AllArgsConstructor
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 鉴权失败处理类
     */
    private final ResetAccessDeniedHandler accessDeniedHandler = new ResetAccessDeniedHandler();

    /**
     * 未认证处理类
     */
    private final ResetAuthenticationEntryPoint authenticationEx = new ResetAuthenticationEntryPoint();
    private final JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    private final KCUserService KCUserService;

    private final UserDetailsService userDetailsService;

    private final CorsFilter corsFilter;
    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */


    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {


        httpSecurity
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers(WhiteUrlsConstants.permitAllUrls).permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();



        // 添加自定义认证失败处理器及自定义权限失败处理器
        httpSecurity.exceptionHandling()
                .authenticationEntryPoint(authenticationEx)
                .accessDeniedHandler(accessDeniedHandler);

        // 允许跨域
        httpSecurity.cors();





        // 过滤器
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
       httpSecurity.addFilterBefore(corsFilter, WebAsyncManagerIntegrationFilter.class);

    }

    /**
     * 身份认证接口
     */

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(KCUserService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    @Override
    // 对用户的未授信凭据进行认证，认证通过则返回授信状态的凭据，否则将抛出认证异常AuthenticationException
    public AuthenticationManager authenticationManagerBean() throws Exception{
        return super.authenticationManagerBean();
    }
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
